package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.pojo.Deposit;
import org.example.service.DepositService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping("/admin/deposit")
public class DepositController {

    @Autowired
    private DepositService depositService;

    @GetMapping("/list")
    public String list(@RequestParam(value = "savingName", required = false) String savingName, Model model) {
        LambdaQueryWrapper<Deposit> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(savingName)) {
            wrapper.like(Deposit::getSavingName, savingName);
        }
        List<Deposit> deposits = depositService.list(wrapper);
        model.addAttribute("deposits", deposits);
        model.addAttribute("savingName", savingName); // 查询回显
        return "/admin/deposit/list";
    }
    @GetMapping("/add")
    public String addPage(Model model) {
        model.addAttribute("deposit", new Deposit());
        return "/admin/deposit/add";
    }

    @PostMapping("/save")
    public String add(Deposit deposit) {
        depositService.save(deposit);
        return "redirect:/admin/deposit/list";
    }

    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable("id") Long id, Model model) {
        Deposit deposit = depositService.getById(id);
        model.addAttribute("deposit", deposit);
        return "/admin/deposit/edit";
    }

    @PostMapping("/update")
    public String update(Deposit deposit) {
        depositService.updateById(deposit);
        return "redirect:/admin/deposit/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id) {
        depositService.removeById(id);
        return "redirect:/admin/deposit/list";
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<Deposit> deposits = depositService.list();
        response.setContentType("text/csv;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=deposit.csv");
        PrintWriter writer = response.getWriter();
        writer.println("存款编号,存款名称,描述");
        for (Deposit d : deposits) {
            writer.printf("%d,%s,%s%n", d.getSavingId(), d.getSavingName(), d.getDescrip());
        }
        writer.flush();
        writer.close();
    }
}